<?php

/*
 * litchicms
 * Copyright (C) ${date} Author: tiefa(539247@qq.com)
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
!defined('BRK') && exit("!");

require 'attachment.fun.php';

if (!function_exists('Component_ui_attachment')) {

    function Component_ui_attachment($arr=NULL) {

        if (key_exists('uploadfile', $GLOBALS['RT']['v']) && ($GLOBALS['RT']['v']['uploadfile'] = 'yes')) {
            Component_attachment_upload();
            exit;
        }
        if (key_exists('deletefile', $GLOBALS['RT']['v']) && ($GLOBALS['RT']['v']['deletefile'] = 'yes')) {
            Component_attachment_delete();
            exit;
        }
        if (key_exists('imgcut', $GLOBALS['RT']['v']) && ($GLOBALS['RT']['v']['imgcut'] = 'yes')) {
            Component_attachment_imgcut();
            exit;
        }
        if (key_exists('imgzoom', $GLOBALS['RT']['v']) && ($GLOBALS['RT']['v']['imgcut'] = 'yes')) {
            Component_attachment_imgzoom();
            exit;
        }
        if (key_exists('attachmentchangename', $GLOBALS['RT']['v']) && ($GLOBALS['RT']['v']['attachmentchangename'] = 'yes')) {
            Component_attachment_changename();
            exit;
        }

        //
        if (empty($GLOBALS['RECORD_ID'])) {
            $DATA_ID = !empty($arr['id']) ? $arr['id'] : 0;
        } else {
            $DATA_ID = $GLOBALS['RECORD_ID'];
        }

        $DEFAULTATTACHMENTS = $DEFAULTATTACHMENTSINPUT = "";
        
        $rs=brk_select_join(
                'attachment,attach_relationships',
                '{0}.*',
                "INNER JOIN {1} ON {0}.attach_id={1}.attach_id
                 WHERE {1}.collection_id=".$GLOBALS['COLLECTION_ID']."
                 AND {1}.data_id=".$DATA_ID."
                 ");

        if ($rs) {
            $DEFAULTATTACHMENTS = array();
            while ($row = $GLOBALS['Db']->fetch_array($rs)) {
                $row["attach_path"] = buildUrl($row["attach_path"]);
                $row["attach_sys_thumb"] = buildUrl($row["attach_sys_thumb"]);
                $row["attach_thumb"] = buildUrl($row["attach_thumb"]);
                $DEFAULTATTACHMENTS[] = $row;
                $DEFAULTATTACHMENTSINPUT.="<input type='hidden' value='" . $row['attach_id'] . "' name='Component[attachment][ids][]'>";
            }
        }
        $html = file_get_contents(SYSTEM . "include/Component/optional/attachment/html.html");
        $html = str_replace('{DEFAULTATTACHMENTS}', json_encode($DEFAULTATTACHMENTS), $html);
//        $html = str_replace('{DEFAULTATTACHMENTSINPUT}', $DEFAULTATTACHMENTSINPUT, $html);
        $html = str_replace('{DEFAULTATTACHMENTSINPUT}', "", $html);


        //
        return $html;
    }

}

$BRK_GLOBAL['ComponentValidationFunction'][] = 'Component_Validation_attachment';
$BRK_GLOBAL['ComponentEndingFunction'][] = 'Component_Ending_attachment';

if (!function_exists('Component_Validation_attachment')) {

    function Component_Validation_attachment() {
        return TRUE;
    }

}

if (!function_exists('Component_Ending_attachment')) {

    function Component_Ending_attachment() {
        if (!key_exists('attachment', $_POST['Component'])) {
            return TRUE;
        }
        if (!key_exists('ids', $_POST['Component']['attachment'])) {
            return TRUE;
        }
        if (is_array($ids = $_POST['Component']['attachment']['ids'])) {
            /*            if (empty($GLOBALS['RECORD_ID'])) {
              $DATA_ID = !empty($arr['id']) ? $arr['id'] : 0;
              } else {
              $DATA_ID = $GLOBALS['RECORD_ID'];
              }
              foreach ($ids as $k => $v) {
              if (($v = intval($v)) == 0) {
              unset($ids[$k]);
              } else {
              $ids[$k] = $v;
              }
              }
              //TODO : 检测附件id是否存在
              $dataarr = array(
              'attach_str' => implode(",", $ids),
              'collection_id' => $GLOBALS['COLLECTION_ID'],
              'data_id' => $DATA_ID
              );

              brk_delete('attach_relationships', "WHERE collection_id='" . $GLOBALS['COLLECTION_ID'] . "' AND data_id='" . $DATA_ID . "'");
              brk_insert('attach_relationships', $dataarr); */
        }
        return TRUE;
    }

}

if (!function_exists('Component_attachment_upload')) {

    function Component_attachment_upload() {

        ob_header_char();
        if (empty($_FILES) || implode('', $_FILES['attachment_files']['tmp_name']) == '') {
            exit("出错啦,没有选择没有文件,或者服务器超时<script language='javascript' type='text/javascript'>window.parent.hide_pop()</script>");
        }

        $success_files = array();

        foreach ($_FILES['attachment_files']['tmp_name'] as $k => $v) {
            if (empty($v)) {
                continue;
            }
            $file = array();
            $file['name'] = $_FILES['attachment_files']['name'][$k];
            $file['type'] = $_FILES['attachment_files']['type'][$k];
            $file['tmp_name'] = $_FILES['attachment_files']['tmp_name'][$k];
            $file['error'] = $_FILES['attachment_files']['error'][$k];
            $file['size'] = $_FILES['attachment_files']['size'][$k];
            $file['private_or_public'] = empty($_POST['private_or_public']) ? 0 : 1;
            $file['attachment_description'] = empty($_POST['attachment_description'][$k]) ? $file['name'] : $_POST['attachment_description'][$k];
            $file['suffix'] = empty($_POST['attachment_suffix'][$k]) ? "" : '.' . $_POST['attachment_suffix'][$k];

            //attachment_type private
            //attachment_description
            //attachment_suffix

            $reArr = attachment_move($file);
            if ($reArr['re'] === FALSE) {
                echo $reArr['name'] . " " . $reArr['error'] . "<br/>";
            } else {
                $reArr['dataarr']["attach_path"] = buildUrl($reArr['dataarr']["attach_path"]);
                $reArr['dataarr']["attach_sys_thumb"] = buildUrl($reArr['dataarr']["attach_sys_thumb"]);
                $reArr['dataarr']["attach_thumb"] = buildUrl($reArr['dataarr']["attach_thumb"]);
                $success_files[] = $reArr['dataarr'];
                echo $reArr['name'] . "上传成功<br/><script language='javascript' type='text/javascript'>window.parent.hide_pop()</script>";
            }
        }


        if (!empty($success_files)) {
            echo "<script language='javascript' type='text/javascript'>window.parent.upload_insert_to_select(" . json_encode($success_files) . ")</script>";
        }
    }

}


if (!function_exists('Component_attachment_delete')) {

    function Component_attachment_delete() {
        ob_header_char();
        if ($one = Component_attachment_action_rigth($_POST['attachment_id'])) {
            brk_delete('attachment', "WHERE attach_id=" . intval($_POST['attachment_id']));
            if ($one['attach_sys_suffix'] != '.attach') {
                is_file($file = BRK . $one['attach_sys_thumb']) && unlink($file);
                is_file($file = BRK . $one['attach_thumb']) && unlink($file);
            }
            is_file($file = BRK . $one['attach_path']) && unlink($file);
            $array = array_merge(array("status" => TRUE), $one);
            echo json_encode($array);
        }
    }

}

if (!function_exists('Component_attachment_imgcut')) {

    function Component_attachment_imgcut() {
        ob_header_char();
        $left = intval($_POST['left']);
        $top = intval($_POST['top']);
        $width = intval($_POST['width']);
        $height = intval($_POST['height']);
        if ($left < 0 || $top < 0 || $width < 0 || $height < 0) {
            echo json_encode(array("status" => false));
            exit;
        }
        if ($one = Component_attachment_action_rigth($_POST['attachment_id'])) {
            if (in_array($one['attach_sys_suffix'], array('.jpg', '.png'))) {
                if (attachment_cut(BRK . $one['attach_path'], $width, $height, $left, $top)) {
                    attachment_thumb(BRK . $one['attach_path'], 40, 40);
                    attachment_thumb(BRK . $one['attach_path'], 120, 120);

                    $one["attach_sys_thumb"] = buildUrl($one["attach_sys_thumb"]);

                    $array = array_merge(array("status" => TRUE), $one);
                    echo json_encode($array);
                    exit;
                }
            }
            echo json_encode(array("status" => false));
            exit;
        }
    }

}


if (!function_exists('Component_attachment_imgzoom')) {

    function Component_attachment_imgzoom() {
        ob_header_char();
        $width = intval($_POST['width']);
        $height = intval($_POST['height']);
        $mustUseSet = empty($_POST['mustUseSet']) ? FALSE : TRUE;
        if ($width < 0 || $height < 0) {
            echo json_encode(array("status" => false));
            exit;
        }
        if ($one = Component_attachment_action_rigth($_POST['attachment_id'])) {
            if (in_array($one['attach_sys_suffix'], array('.jpg', '.png'))) {
                $one['attach_thumb'] = attachment_thumb(BRK . $one['attach_path'], $width, $height, $mustUseSet);
                brk_update('attachment', array('attach_thumb' => $one['attach_thumb']), "WHERE attach_id=" . $one['attach_id']);

                $one["attach_thumb"] = buildUrl($one["attach_thumb"]);

                $array = array_merge(array("status" => TRUE), $one);
                echo json_encode($array);
                exit;
            }
        }
        echo json_encode(array("status" => false));
        exit;
        /*
          {"status":true,
         * "attach_id":"140",
         * "attach_type":".jpg",
         * "attach_sys_suffix":".jpg",
         * "attach_sys_name":"127940809886159.jpg",
         * "attach_name":"89f602d902fc4cf038012f24",
         * "attach_time":"1279408098",
         * "attach_user":"1",
         * "attach_isimg":"1",
         * "attach_size":"92143",
         * "attach_path":"data\/tt\/10\/7\/127940809886159.jpg",
         * "attach_sys_thumb":"data\/tt\/10\/7\/127940809886159_40_40.jpg",
         * "attach_thumb":"data\/tt\/10\/7\/127940809886159_120_120.jpg",
         * "attach_right":"0",
         * "attach_click":"0"}
         */
    }

}



if (!function_exists('Component_attachment_changename')) {

    function Component_attachment_changename() {
        ob_header_char();
        if (empty($_POST['newname'])) {
            echo json_encode(array("status" => false));
            exit;
        }
        if ($one = Component_attachment_action_rigth($_POST['attachment_id'])) {
            if (brk_update('attachment', array('attach_name' => $_POST['newname']), "WHERE attach_id=" . intval($_POST['attachment_id']))) {
                echo json_encode(array("status" => true));
                exit;
            }
        }
        echo json_encode(array("status" => false));
        exit;
    }

}